// 文件路径: /app/(auth)/login/page.tsx
"use client"; // 标记为客户端组件
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { useRouter } from "next/navigation";
import axios from "axios";
import { httpGet, httpPost } from '../../utils/httpUtils';

const loginSchema = z.object({
    username: z.string().min(1, "用户名不能为空"),
    password: z.string().min(6, "密码至少需要 6 个字符"),
});

type LoginFormData = z.infer<typeof loginSchema>;

export default function LoginPage() {
    const router = useRouter();
    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm<LoginFormData>({
        resolver: zodResolver(loginSchema),
    });

    const onSubmit = async (data: LoginFormData) => {
        try {
            // 发送登录请求到后端
            // const response = await axios.post("/login", data);
            const responseData = await httpPost<LoginFormData[]>('/login',data);
            debugger
            console.log("返回的data:"+responseData)
            if (responseData.code == "200") {
                localStorage.setItem("token",responseData.data);
                document.cookie = `token=${encodeURIComponent(responseData.data)}; path=/; max-age=36000`; // 设置有效期为 1 小时
                router.push("/"); // 跳转到首页
            } else {
                console.error("登录失败:", responseData.msg);
                alert(responseData.msg);
            }

            // if (response.data.success) {
            //     // 登录成功后设置 Cookie
            //     document.cookie = `token=${response.data.token}; path=/`;
            //     router.push("/"); // 跳转到首页
            // }
        } catch (error) {
            console.error("登录失败:", error);
            alert("用户名或密码错误");
        }
    };

    return (
        <div style={{
            backgroundImage: "url('/background.png')",
            backgroundSize: 'cover',
            backgroundRepeat: 'no-repeat',
            backgroundPosition: 'center',
            width: '100vw',
            height: '100vh',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
        }} className="flex min-h-screen items-center justify-center bg-gray-100">
            <div className="w-full max-w-md p-8 space-y-4 bg-white rounded-lg shadow-lg">
                <h2 className="text-2xl font-bold text-center">课堂实时监测系统</h2>
                <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
                    <div>
                        <label htmlFor="username" className="block text-sm font-medium">
                            用户名
                        </label>
                        <input
                            id="username"
                            {...register("username")}
                            className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                        />
                        {errors.username && (
                            <p className="text-red-500 text-sm">{errors.username.message}</p>
                        )}
                    </div>
                    <div>
                        <label htmlFor="password" className="block text-sm font-medium">
                            密码
                        </label>
                        <input
                            id="password"
                            type="password"
                            {...register("password")}
                            className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                        />
                        {errors.password && (
                            <p className="text-red-500 text-sm">{errors.password.message}</p>
                        )}
                    </div>
                    <button
                        type="submit"
                        className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                        登录
                    </button>
                </form>
            </div>
        </div>
    );
}